package ldh.common.testui.controller;

import com.jfoenix.controls.*;
import com.jfoenix.validation.RequiredFieldValidator;
import com.jfoenix.validation.base.ValidatorBase;
import javafx.application.Platform;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.Pane;
import javafx.scene.layout.Region;
import ldh.common.testui.dao.GetResultValueDao;
import ldh.common.testui.model.GetResultValue;
import ldh.common.testui.model.TreeNode;
import ldh.common.testui.util.*;
import ldh.common.testui.vo.VarModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.math.BigDecimal;
import java.net.URL;
import java.util.*;
import java.util.stream.Collectors;

public class GetResultValueController extends BaseController implements Initializable {

    private static final Logger LOGGER = LoggerFactory.getLogger(GetResultValueController.class);

//    @FXML private JFXTextArea checkBeanTextArea;
    @FXML private TableView<GetResultValue> dataTableView;

    @FXML private Region tablePane;
    @FXML private Region textPane;

    @FXML private Pane stackPane;
    @FXML private ScrollPane listPane;
    @FXML private ScrollPane paramPane;
    @FXML private GridPane editPane;

    @FXML private JFXTextField nameTextField;
    @FXML private JFXTextField valueTextField;
    @FXML private JFXComboBox<String> typeComboBox;

    private GetResultValue editData = null;  // 修改
    private List<ValidatorBase> validatorBases = new ArrayList<>();

    @Override
    public void setTreeItem(TreeItem<TreeNode> treeItem) {
        super.setTreeItem(treeItem);
        loadData();
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        stackPane.getChildren().remove(paramPane);

        RequiredFieldValidator nameValidator = JFoenixUtil.createValidatorBase(new RequiredFieldValidator(), nameTextField);
        RequiredFieldValidator valueValidator = JFoenixUtil.createValidatorBase(new RequiredFieldValidator(), valueTextField);

        validatorBases.addAll(Arrays.asList(nameValidator, valueValidator));

        initTypeComboBox();
    }

    private void initTypeComboBox() {
        List<Class> classList = Arrays.asList(Integer.class, Byte.class, String.class, Long.class, Double.class, BigDecimal.class, Date.class);
        classList.forEach(clazz->{
            typeComboBox.getItems().add(clazz.getName());
        });
    }

    public void addBeanData(ActionEvent actionEvent) {
        editData = null;
        nameTextField.setText("");
        valueTextField.setText("");
        JFXDialog dialog = DialogUtil.createDialog(paramPane, "添加参数", (jfxDialog, jfxDialogLayout) -> {
            JFXButton saveButton = new JFXButton("保存");
            saveButton.getStyleClass().add("dialog-accept");
            saveButton.setOnAction(e1->saveData(jfxDialog));
            return Arrays.asList(saveButton);
        });
        dialog.show();
    }

    public void editBeanData(ActionEvent actionEvent) {
        GetResultValue data = dataTableView.getSelectionModel().getSelectedItem();
        if (data == null) return;
        editData = data;

        nameTextField.setText(data.getName());
        valueTextField.setText(data.getValue());
        JFXDialog dialog = DialogUtil.createDialog(paramPane, "修改参数", (jfxDialog, jfxDialogLayout) -> {
            JFXButton saveButton = new JFXButton("保存");
            saveButton.getStyleClass().add("dialog-accept");
            saveButton.setOnAction(e1->saveData(jfxDialog));
            return Arrays.asList(saveButton);
        });
        dialog.show();
    }

    public void removeData(ActionEvent actionEvent) {
        GetResultValue data = dataTableView.getSelectionModel().getSelectedItem();
        if (data == null) return;
        editData = null;
        ThreadUtilFactory.getInstance().submit(()->{
            try {
                GetResultValueDao.delete(data);
                Platform.runLater(()->{
                    dataTableView.getItems().remove(data);
                });
            } catch (Exception e) {
                Platform.runLater(()->DialogUtil.alert("删除数据失败", Alert.AlertType.ERROR));
            }
            return null;
        }, null);
    }

    private void loadData() {
        Task<Void> task = new Task() {

            @Override
            protected Object call() throws Exception {
                try {
                    List<GetResultValue> getResultValues = GetResultValueDao.getByTreeNodeId(treeItem.getValue().getId());
                    Platform.runLater(()->{
                        dataTableView.getItems().clear();
                        dataTableView.getItems().addAll(getResultValues);
                    });
                    return null;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };
//        task.setOnSucceeded(e->{
//            TableViewUtil.autoResizeColumns(dataTableView);
//        });
        ThreadUtilFactory.getInstance().submit(task);
    }


    private void saveData(JFXDialog jfxDialog) {
        validatorBases.forEach(validatorBase -> validatorBase.validate());
        long errorCount = validatorBases.stream().filter(validatorBase -> validatorBase.getHasErrors()).count();
        if (errorCount > 0) {
            DialogUtil.alert("请按照要求填写", Alert.AlertType.ERROR);
            return;
        }
        GetResultValue newGetResultValue = new GetResultValue();
        newGetResultValue.setName(nameTextField.getText().trim());
        newGetResultValue.setValue(valueTextField.getText().trim());
        newGetResultValue.setTreeNodeId(treeItem.getValue().getId());
        newGetResultValue.setType(typeComboBox.getSelectionModel().getSelectedItem());
        if (editData != null) {
            newGetResultValue.setId(editData.getId());
        }
        ThreadUtilFactory.getInstance().submit(()->{
            GetResultValueDao.save(newGetResultValue);
            Platform.runLater(()->{
                if (newGetResultValue.getId() != null) {
                    List<GetResultValue> getResultValues = dataTableView.getItems();
                    getResultValues.remove(editData);
                    getResultValues.add(newGetResultValue);
                    getResultValues = getResultValues.stream().sorted(Comparator.comparing(getResultValue -> getResultValue.getId())).collect(Collectors.toList());
                    dataTableView.getItems().clear();
                    dataTableView.getItems().addAll(getResultValues);
                } else {
                    dataTableView.getItems().add(newGetResultValue);
                }
//                UiUtil.transitionPane(paramPane, listPane, (Void)->{});
                jfxDialog.close();
            });

            return null;
        }, null);
    }

    private boolean checkCheckName(String checkName) {
        if (checkName == null || checkName.equals("")) {
            return false;
        }
        if(checkName.equals("${result}")) return true;
        String varName = VarUtil.getVarName(checkName);
        if (varName == null) return false;
        VarUtil.cacheVar(treeItem);
        VarModel varModel = VarFactory.getInstance().getCache(treeItem, varName);
        if (varModel == null) {
            return false;
        }
        return true;
    }

}
